package com.supermap.dataservice.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

public class ImageUtil {

    /**
     * 保存文件，直接以multipartFile形式
     *
     * @param multipartFile
     * @param path          文件保存绝对路径
     * @param type
     * @return 返回文件名
     * @throws IOException
     */
    public static String saveImg(MultipartFile multipartFile, String path, String type) {
        path = path + "/" + type;
        if (multipartFile.isEmpty() || !multipartFile.getContentType().contains("")) {
            return null;
        }
        String fileName = null;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileInputStream fileInputStream = null;
        BufferedOutputStream bos = null;
        try {
            fileInputStream = (FileInputStream) multipartFile.getInputStream();
            fileName = Constants.getUUID() + ".png";
            bos = new BufferedOutputStream(new FileOutputStream(path + File.separator + fileName));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            bos.flush();
        } catch (IOException e) {
            fileName = null;
        } finally {
            try {
                bos.close();
            } catch (IOException e) {
                fileName = fileName;
            }
        }
        return fileName == null ? null : type + "/" + fileName;
    }
}

